<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Android自定义View-01 绘图基础 | 码行</title><meta name="author" content="Carl Su"><meta name="copyright" content="Carl Su"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="基本图形绘制 Paint 画笔，设置 画笔大小、粗细、画笔颜色、透明度、字体等样式 Canvas 画布，画出成品的东西，如圆形、矩形、文字等。  Paint基础使用： import android.annotation.SuppressLintimport android.content.Contextimport android.graphics.Canvasimport android.gra">
<meta property="og:type" content="article">
<meta property="og:title" content="Android自定义View-01 绘图基础">
<meta property="og:url" content="https://devsu.top/posts/febb5061/index.html">
<meta property="og:site_name" content="码行">
<meta property="og:description" content="基本图形绘制 Paint 画笔，设置 画笔大小、粗细、画笔颜色、透明度、字体等样式 Canvas 画布，画出成品的东西，如圆形、矩形、文字等。  Paint基础使用： import android.annotation.SuppressLintimport android.content.Contextimport android.graphics.Canvasimport android.gra">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s2.loli.net/2023/03/14/GzPHlY2aEkeVO1M.png">
<meta property="article:published_time" content="2020-08-05T01:59:14.000Z">
<meta property="article:modified_time" content="2023-03-30T01:32:24.521Z">
<meta property="article:author" content="Carl Su">
<meta property="article:tag" content="Android">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s2.loli.net/2023/03/14/GzPHlY2aEkeVO1M.png"><link rel="shortcut icon" href="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"><link rel="canonical" href="https://devsu.top/posts/febb5061/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6243425e2ecb037931274c4ca1db3132";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Carl Su","link":"链接: ","source":"来源: 码行","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Android自定义View-01 绘图基础',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-30 09:32:24'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s2.loli.net/2023/03/09/QrI9mgJ4XlbEPzN.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">169</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">38</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('https://s2.loli.net/2023/03/14/GzPHlY2aEkeVO1M.png')"><nav id="nav"><span id="blog-info"><a href="/" title="码行"><img class="site-icon" src="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"/><span class="site-name">码行</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Android自定义View-01 绘图基础</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-08-05T01:59:14.000Z" title="发表于 2020-08-05 09:59:14">2020-08-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-30T01:32:24.521Z" title="更新于 2023-03-30 09:32:24">2023-03-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/">Android</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/%E8%87%AA%E5%AE%9A%E4%B9%89View/">自定义View</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Android自定义View-01 绘图基础"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="基本图形绘制"><a href="#基本图形绘制" class="headerlink" title="基本图形绘制"></a>基本图形绘制</h2><ul>
<li><code>Paint</code> 画笔，设置 画笔大小、粗细、画笔颜色、透明度、字体等样式</li>
<li><code>Canvas</code> 画布，画出成品的东西，如圆形、矩形、文字等。</li>
</ul>
<h3 id="Paint"><a href="#Paint" class="headerlink" title="Paint"></a>Paint</h3><p>基础使用：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> android.<span class="keyword">annotation</span>.SuppressLint</span><br><span class="line"><span class="keyword">import</span> android.content.Context</span><br><span class="line"><span class="keyword">import</span> android.graphics.Canvas</span><br><span class="line"><span class="keyword">import</span> android.graphics.Color</span><br><span class="line"><span class="keyword">import</span> android.graphics.Paint</span><br><span class="line"><span class="keyword">import</span> android.util.AttributeSet</span><br><span class="line"><span class="keyword">import</span> android.view.View</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BasicView</span>: <span class="type">View</span> &#123;</span><br><span class="line">    <span class="keyword">constructor</span>(context: Context): <span class="keyword">super</span>(context)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">constructor</span>(context: Context, atts: AttributeSet): <span class="keyword">super</span>(context,atts)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">constructor</span>(context: Context, atts: AttributeSet, defStyle: <span class="built_in">Int</span>): <span class="keyword">super</span>(context,atts,defStyle)</span><br><span class="line"></span><br><span class="line">    <span class="meta">@SuppressLint(<span class="string">&quot;DrawAllocation&quot;</span>)</span></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onDraw</span><span class="params">(canvas: <span class="type">Canvas</span>?)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onDraw(canvas)</span><br><span class="line">        <span class="comment">//设置画笔的基本属性</span></span><br><span class="line">        <span class="keyword">val</span> paint = Paint()</span><br><span class="line">        paint.run &#123;</span><br><span class="line">            <span class="comment">//设置画笔颜色</span></span><br><span class="line">            color = Color.RED</span><br><span class="line">            <span class="comment">//设置画笔填充样式</span></span><br><span class="line">            style = Paint.Style.STROKE</span><br><span class="line">            <span class="comment">//设置画笔宽度</span></span><br><span class="line">            strokeWidth = <span class="number">50f</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//画圆 cx: 圆心x坐标，cy: 圆心y坐标</span></span><br><span class="line">        canvas?.drawCircle(<span class="number">190f</span>,<span class="number">200f</span>,<span class="number">150f</span>,paint)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>具体代码见<a target="_blank" rel="noopener" href="https://github.com/winstone-su/CustomView/blob/master/basicdrawing/src/main/java/com/carl/sample/basicdrawing/BasicView.kt">Github</a>： </p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">Paint</span> <span class="variable">paint</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Paint</span>();</span><br><span class="line">paint.setColor(Color.GREEN); <span class="comment">//设置画笔颜色</span></span><br><span class="line">paint.setStyle(Paint.Style.FILL);	<span class="comment">//设置画笔样式 FILL : 填充, STROKE : 描边, FILL_AND_STROKE : 填充和描边</span></span><br><span class="line">paint.setStrokeWidth(<span class="number">5</span>); <span class="comment">//画笔宽度 px</span></span><br></pre></td></tr></table></figure>

<p>下面绘制一大一小两个圆，并且将这两个圆叠加起来，上方的圆半透明，代码如下:</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">val</span> paint = Paint()</span><br><span class="line">paint.run &#123;</span><br><span class="line">    <span class="comment">//设置画笔颜色</span></span><br><span class="line">    color = Color.RED</span><br><span class="line">    <span class="comment">//设置画笔填充样式</span></span><br><span class="line">    style = Paint.Style.FILL</span><br><span class="line">    <span class="comment">//设置画笔宽度</span></span><br><span class="line">    strokeWidth = <span class="number">50f</span></span><br><span class="line">&#125;</span><br><span class="line">canvas?.drawCircle(<span class="number">190f</span>,<span class="number">200f</span>,<span class="number">150f</span>,paint)</span><br><span class="line">paint.color = <span class="number">0x7EFFFF00</span></span><br><span class="line">canvas?.drawCircle(<span class="number">190f</span>,<span class="number">200f</span>,<span class="number">100f</span>,paint)</span><br></pre></td></tr></table></figure>

<p>效果如下：</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://s2.loli.net/2023/03/29/dyVXM2egIHL31xl.png" alt="paint1-1"></p>
<p><strong>paint.style</strong></p>
<p>完整的函数生命如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setStyle</span><span class="params">(Style style)</span> &#123; &#125;</span><br></pre></td></tr></table></figure>

<p>该函数用于设置填充样式，对于文字和集合图形都有效。style的取值如下：</p>
<ul>
<li>Paint.Style.FILL	仅填充内部</li>
<li>Paint.Style.FILL_AND_STROKE    填充内部和描边</li>
<li>Paint.Style.STROKE    仅描边</li>
</ul>
<p>下面以绘制圆形为例，看一下这三个不同的类型，效果图如下（代码见<a target="_blank" rel="noopener" href="https://github.com/winstone-su/CustomView/blob/master/basicdrawing/src/main/java/com/carl/sample/basicdrawing/BasicView2.kt">Github</a>）</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://s2.loli.net/2023/03/29/edZHyrLGwmDXV9W.png" alt="Paint.Style"></p>
<p>明显可见，<code>FILL_AND_STROKE</code>是<code>FILL</code>和<code>STROKE</code>叠加在一起的效果，<code>FILL_AND_STROKE</code>比<code>FILL</code>多了一个描边的宽度。</p>
<p><strong>paint.strokeWidth</strong></p>
<p>完整的函数声明如下:</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setStrokeWidth</span><span class="params">(<span class="type">float</span> width)</span></span><br></pre></td></tr></table></figure>

<p>设置用于描边宽度，单位是px。当画笔的<code>Style</code>是<code>FILL</code>、<code>STROKE</code>、<code>FILL_AND_STROKE</code>时有效。</p>
<h3 id="Canvas"><a href="#Canvas" class="headerlink" title="Canvas"></a>Canvas</h3><h4 id="设置画布背景"><a href="#设置画布背景" class="headerlink" title="设置画布背景"></a>设置画布背景</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">canvas.drawColor(Color.GREEN);  <span class="comment">// drawColor(@ColorInt int color)</span></span><br><span class="line">canvas.drawRGB(<span class="number">255</span>,<span class="number">0</span>,<span class="number">255</span>);      <span class="comment">//drawRGB(int r, int g, int b) </span></span><br><span class="line">canvas.drawARGB(<span class="number">0xFF</span>,<span class="number">0xFF</span>,<span class="number">0</span>,<span class="number">0</span>); <span class="comment">//drawARGB(int a, int r, int g, int b)</span></span><br></pre></td></tr></table></figure>

<p>其中<code>drawColor()</code>函数中参数<code>color</code>的取值必须是8位的0xAARRGGBB样式颜色值。</p>
<p><code>drawARGB()</code>函数允许分别传入A、R、G、B分量，每个颜色值得取值范围都是0<del>255(对应十六进制数0x00</del>0xFF)，内部会通过这些颜色分量构造出对应的颜色值。</p>
<p><code>drawRGB()</code>函数只允许传入R、G、B分量，透明度Alpha的取值为<code>255</code>。</p>
<p>比如将画布默认颜色填充为蓝色。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line">canvas?.run &#123;</span><br><span class="line">    drawColor(Color.BLUE)</span><br><span class="line">    <span class="comment">//这两种写法也可以</span></span><br><span class="line">    <span class="comment">// drawARGB(0xFF,0x00,0x00,0xFF)</span></span><br><span class="line">    <span class="comment">// drawRGB(0x00,0x00,0xFF)</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://s2.loli.net/2023/03/29/Kch2Bb71TJ3Ruxj.png" alt="canvas"></p>
<h4 id="画直线"><a href="#画直线" class="headerlink" title="画直线"></a>画直线</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">drawLine</span><span class="params">(<span class="type">float</span> startX, <span class="type">float</span> startY, <span class="type">float</span> stopX, <span class="type">float</span> stopY, <span class="meta">@NonNull</span> Paint paint)</span></span><br></pre></td></tr></table></figure>

<p>参数含义:</p>
<ul>
<li>startX：起始点X坐标</li>
<li>startY：起始点Y坐标</li>
<li>stopX：终点X坐标</li>
<li>stopY：终点Y坐标</li>
</ul>
<p>示例如下：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line">paint.run &#123;</span><br><span class="line">    color = Color.RED</span><br><span class="line">    style = Paint.Style.FILL_AND_STROKE</span><br><span class="line">    strokeWidth = <span class="number">50f</span></span><br><span class="line">&#125;</span><br><span class="line">canvas?.run &#123;</span><br><span class="line">    drawLine(<span class="number">100f</span>,<span class="number">100f</span>,<span class="number">200f</span>,<span class="number">200f</span>,paint)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当设置不同的<code>Style</code>类型时，效果如下图所示。</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://s2.loli.net/2023/03/29/1FEilmgY4yRGrZB.png" alt="image-20230329171700360"></p>
<p>可以看到，直线的粗细和笔画的<code>Style</code>是没有关系的。</p>
<p>当设置不同的<code>strokeWidth</code>时，效果如下：</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://s2.loli.net/2023/03/29/GXqFEfJmSvkPbL6.png" alt="canvas-strokeWidth"></p>
<p>可见，直线的粗细与<code>paint.strokeWidth</code>有直接关系。所以，一般而言，<code>paint.strokeWidth</code>在<code>Style</code>起作用时，用于设置描边宽度；在Style不起作用时，用于设置笔画宽度。</p>
<h4 id="画点"><a href="#画点" class="headerlink" title="画点"></a>画点</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">drawPoint</span><span class="params">(<span class="type">float</span> x, <span class="type">float</span> y, <span class="meta">@NonNull</span> Paint paint)</span></span><br></pre></td></tr></table></figure>

<ul>
<li>float x：点的X坐标</li>
<li>float y：点的Y坐标</li>
</ul>
<p>示例如下：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">val</span> paint = Paint()</span><br><span class="line">paint.run &#123;</span><br><span class="line">	color = Color.CYAN</span><br><span class="line">    strokeWidth = <span class="number">15f</span></span><br><span class="line">&#125;</span><br><span class="line">canvas?.drawPoint(<span class="number">100f</span>,<span class="number">100f</span>,paint)</span><br></pre></td></tr></table></figure>

<p>代码很简单，就是在(100,100)的位置画了一个点。同样点的大小只与<code>paint.strokeWidth</code>有关，而与<code>paint.style</code>无关</p>
<h4 id="矩形"><a href="#矩形" class="headerlink" title="矩形"></a>矩形</h4><p><strong>工具类介绍</strong></p>
<p><code>Rect</code>F和<code>Rect</code>区别：<code>RectF</code>里面参数是float类型，<code>Rect</code>里面参数是int类型&#96;</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="title function_">RectF</span><span class="params">()</span> </span><br><span class="line"><span class="keyword">public</span> <span class="title function_">RectF</span><span class="params">(<span class="type">float</span> left, <span class="type">float</span> top, <span class="type">float</span> right, <span class="type">float</span> bottom)</span> </span><br><span class="line"><span class="keyword">public</span> <span class="title function_">RectF</span><span class="params">(<span class="meta">@Nullable</span> RectF r)</span> </span><br><span class="line"><span class="keyword">public</span> <span class="title function_">RectF</span><span class="params">(<span class="meta">@Nullable</span> Rect r)</span> </span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="title function_">Rect</span><span class="params">()</span></span><br><span class="line"><span class="keyword">public</span> <span class="title function_">Rect</span><span class="params">(<span class="type">int</span> left, <span class="type">int</span> top, <span class="type">int</span> right, <span class="type">int</span> bottom)</span></span><br><span class="line"><span class="keyword">public</span> <span class="title function_">Rect</span><span class="params">(<span class="meta">@Nullable</span> Rect r)</span></span><br></pre></td></tr></table></figure>

<p>可以看到<code>RectF</code>和<code>Rect</code>的构造函数基本相同，不同的只是<code>RectF</code>所保存的数值类型是float类型，而<code>Rect</code>所保存的数值类型是int类型。</p>
<p>一般而言，要构造一个矩形结构，可以通过以下两种方式来实现。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="comment">//直接构造</span></span><br><span class="line"><span class="keyword">val</span> rect = Rect(<span class="number">10</span>,<span class="number">10</span>,<span class="number">100</span>,<span class="number">100</span>)</span><br><span class="line"><span class="comment">//间接构造</span></span><br><span class="line"><span class="keyword">val</span> rect1 = Rect()</span><br><span class="line">rect1.<span class="keyword">set</span>(<span class="number">10</span>,<span class="number">10</span>,<span class="number">100</span>,<span class="number">100</span>)</span><br></pre></td></tr></table></figure>



<p><strong>绘制方法</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">drawRect</span><span class="params">(<span class="meta">@NonNull</span> RectF rect, <span class="meta">@NonNull</span> Paint paint)</span>  </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">drawRect</span><span class="params">(<span class="meta">@NonNull</span> Rect r, <span class="meta">@NonNull</span> Paint paint)</span>  </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">drawRect</span><span class="params">(<span class="type">float</span> left, <span class="type">float</span> top, <span class="type">float</span> right, <span class="type">float</span> bottom, <span class="meta">@NonNull</span> Paint paint)</span> </span><br></pre></td></tr></table></figure>

<h3 id="路径-Path"><a href="#路径-Path" class="headerlink" title="路径 (Path)"></a>路径 (Path)</h3></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://devsu.top">Carl Su</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://devsu.top/posts/febb5061/">https://devsu.top/posts/febb5061/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://devsu.top" target="_blank">码行</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Android/">Android</a></div><div class="post_share"><div class="social-share" data-image="https://s2.loli.net/2023/03/14/GzPHlY2aEkeVO1M.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/d2fda48f/" title="Android自定义View-02 视图动画"><img class="cover" src="https://s2.loli.net/2023/03/14/RLM1qPGF3S6sNnJ.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Android自定义View-02 视图动画</div></div></a></div><div class="next-post pull-right"><a href="/posts/98025dc/" title="2020-07-14-iOS本地化(Swift)"><img class="cover" src="https://img13.51tietu.net/pic/20200118/c2zuvgsebp0c2zuvgsebp0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">2020-07-14-iOS本地化(Swift)</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/be1a9334/" title="Android-在Activity中使用Menu"><img class="cover" src="https://img10.51tietu.net/pic/20191030/k2hqdmpfendk2hqdmpfend.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Android-在Activity中使用Menu</div></div></a></div><div><a href="/posts/59a3d1d6/" title="ConstraintLayout-constraintDimensionRatio属性"><img class="cover" src="https://img0.baidu.com/it/u=2303708579,2686113994&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">ConstraintLayout-constraintDimensionRatio属性</div></div></a></div><div><a href="/posts/f305e41/" title="Android 11 分区存储"><img class="cover" src="https://img9.51tietu.net/pic/20190921/idxelngfttlidxelngfttl.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Android 11 分区存储</div></div></a></div><div><a href="/posts/b79c82/" title="Android优秀开源第三方库"><img class="cover" src="https://img.qingwk.com/images/resource/global/2020/06/09/96961_46896196822_at.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Android优秀开源第三方库</div></div></a></div><div><a href="/posts/aae49b39/" title="Hilt基本使用"><img class="cover" src="https://img1.baidu.com/it/u=1939248509,402303850&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-05</div><div class="title">Hilt基本使用</div></div></a></div><div><a href="/posts/6ed51752/" title="Android Studio 和Lombok插件不兼容问题"><img class="cover" src="https://img0.baidu.com/it/u=1087455262,471122708&fm=253&fmt=auto&app=138&f=JPEG?w=667&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Android Studio 和Lombok插件不兼容问题</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Valine</span><span class="switch-btn"></span><span class="second-comment">Disqus</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div><div><div id="disqus_thread"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E5%9B%BE%E5%BD%A2%E7%BB%98%E5%88%B6"><span class="toc-number">1.</span> <span class="toc-text">基本图形绘制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Paint"><span class="toc-number">1.1.</span> <span class="toc-text">Paint</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Canvas"><span class="toc-number">1.2.</span> <span class="toc-text">Canvas</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AE%BE%E7%BD%AE%E7%94%BB%E5%B8%83%E8%83%8C%E6%99%AF"><span class="toc-number">1.2.1.</span> <span class="toc-text">设置画布背景</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%BB%E7%9B%B4%E7%BA%BF"><span class="toc-number">1.2.2.</span> <span class="toc-text">画直线</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%BB%E7%82%B9"><span class="toc-number">1.2.3.</span> <span class="toc-text">画点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9F%A9%E5%BD%A2"><span class="toc-number">1.2.4.</span> <span class="toc-text">矩形</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%B7%AF%E5%BE%84-Path"><span class="toc-number">1.3.</span> <span class="toc-text">路径 (Path)</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By Carl Su</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">学无止境</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script>function loadDisqus () {
  var disqus_config = function () {
    this.page.url = 'https://devsu.top/posts/febb5061/'
    this.page.identifier = '/posts/febb5061/'
    this.page.title = 'Android自定义View-01 绘图基础'
  };

  window.disqusReset = () => {
    DISQUS.reset({
      reload: true,
      config: disqus_config
    })
  }

  if (window.DISQUS) disqusReset()
  else {
    (function() { 
      var d = document, s = d.createElement('script');
      s.src = 'https://.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
    })();
  }

  document.getElementById('darkmode').addEventListener('click', () => {
    setTimeout(() => window.disqusReset(), 200)
  })
}

if ('Valine' === 'Disqus' || !true) {
  if (true) btf.loadComment(document.getElementById('disqus_thread'), loadDisqus)
  else loadDisqus()
} else {
  function loadOtherComment () {
    loadDisqus()
  }
}
</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>